package classes
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.media.Sound;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.ByteArray;
	
	public class Waveform{
		
		private var _nativeCanvas:Sprite;
		private var _yourCanvas:Sprite;
		private var _timeLine:Sprite;
		private var _maxWidth:Number = 0;
		private var _yourMaxWidth:Number = 0;
		private var _nativeMaxWidth:Number = 0;
		private var _totalNativeSec:Number = 0;
		private var _timeGap:Number = 0;
		public function get yourMaxWidth():Number{ return _yourMaxWidth; }
		public function get naitveMaxWidth():Number{ return _nativeMaxWidth; }
		public function Waveform( nativeCanvas:Sprite, yourCanvas:Sprite, timeLine:Sprite ):void{
			_nativeCanvas = nativeCanvas;
			_yourCanvas = yourCanvas;
			_timeLine = timeLine;
		}
		public function drawYour( src:ByteArray ):void{
			if( !src ) return;
			var half:int = _nativeCanvas.height/2;
			_yourCanvas.graphics.clear();
			src.position = 0;
			_yourCanvas.graphics.lineStyle( 2, 0xF78B56 );
			_yourMaxWidth = draw( src, _yourCanvas )
		}
		public function drawNative( snd:Sound, start:Number, length:Number ):void{
			_nativeCanvas.graphics.clear();
			var ba:ByteArray = new ByteArray();
			snd.extract( ba, length,  start );
			ba.position = 0;
			_nativeCanvas.graphics.lineStyle( 2, 0x329AFF );
			_nativeMaxWidth = draw( ba, _nativeCanvas );
			_totalNativeSec = snd.length/1000;
			_timeGap = _maxWidth / _totalNativeSec; 
		}
		public function drawtimeLine( start:Number, end:Number):void{
			var g:Graphics = _timeLine.graphics;
			var x:Number = 0;
			var y:Number = _timeLine.height;
			var label:TextField;
			var time:int = 0;
			g.lineStyle( 1, 0xDBE0E3 );
			for( var i:int=start, count:int=end ; i<count ; i+=1 ){
				time++;
				x = _timeGap*i;
				g.moveTo( x, 0 );
				g.lineTo( x, y );
				label = new TextField();
				label.wordWrap = false;
				label.autoSize = TextFieldAutoSize.CENTER
				label.textColor = 0xDBE0E3; 
				label.text = time.toString();
				label.x = x-( label.textWidth/2);
				label.y = y;
				_timeLine.addChild( label );
			}
		}
		public function clearYour():void{
			_yourCanvas.graphics.clear();
		}
		private function draw( ba:ByteArray, canvas:Sprite):Number{
			if( !ba ) return 0;
			var half:int = canvas.height/2;
			var minY:int = 10;
			var maxY:int = canvas.height-10;
			var x:Number=0;
			var value:Number;
			canvas.graphics.moveTo(10, half );
			while( ba.bytesAvailable > 0 ){
				value = ba.readFloat() * 500 + half;
				if( value < minY ) value = minY;
				if( value > maxY ) value = maxY;
				//x = ( ( canvas.width - 10 ) - 10 )/( ba.length - 0 )*( ba.position )+10;
				x += 3;
				canvas.graphics.lineTo( x, value );
				ba.position += 18200;
			}
			if( _maxWidth == 0 ) _maxWidth = x;
			canvas.graphics.lineTo( x, half );
			canvas.graphics.lineTo( _maxWidth, half );
			return x;
		}
	}
}